package com.taobao.tbk.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.request.TbkDgItemCouponGetRequest;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkDgItemCouponGetResponse;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;
import com.taobao.tbk.dao.JHSItemDo;
import com.taobao.tbk.dao.JPItemDo;
import com.taobao.tbk.mapper.JHSItemDoMapper;
import com.taobao.tbk.mapper.JPItemDoMapper;
import com.taobao.tbk.utils.StringRedisUtil;
import com.taobao.tbk.utils.TaobaoApiRequestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TbkApiService {

    @Autowired
    private TaobaoApiRequestClient client;

    @Value("${taobao.adzoneid}")
    private Long adzoneId;

    @Value("${taobao.pagesize}")
    private Long pageSize;

    @Autowired
    private ItemProcService itemProcService;

    @Autowired
    private StringRedisUtil stringRedisUtil;

    @Autowired
    private JPItemDoMapper jpItemDoMapper;

    @Autowired
    private JHSItemDoMapper jhsItemDoMapper;


  /**
     * 获取好券清单
     * @param platformId    1：PC，2：无线，默认：1
     * @param catId         类目id
     * @param q             查询词
     * @param pageNo        查询页码
     * @return              查询结果json字符串
     * @throws ApiException
     */
    public String getTbkDgItemCoupon(Long platformId, String catId, String q, Long pageNo) throws ApiException {
        TbkDgItemCouponGetRequest req = new TbkDgItemCouponGetRequest();
        req.setAdzoneId(this.adzoneId);
        req.setPlatform(platformId);
        req.setCat(catId);
        req.setPageSize(this.pageSize);
        req.setQ(q);
        req.setPageNo(pageNo);
        TbkDgItemCouponGetResponse rsp = (TbkDgItemCouponGetResponse)client.execute(req);
//        System.out.println(rsp.getBody());
        return rsp.getBody();
    }

    public String requestTbkDgItem(Long platformId, String catId, String q, Long pageNo) throws ApiException {
        TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
        req.setPageSize(this.pageSize);
        req.setPageNo(pageNo);
        req.setPlatform(platformId);
        req.setCat(catId);
        req.setQ(q);
        req.setHasCoupon(true);
        req.setAdzoneId(this.adzoneId);
        TbkDgMaterialOptionalResponse rsp = (TbkDgMaterialOptionalResponse)client.execute(req);
        itemProcService.processItemStr(rsp.getBody());
        return rsp.getBody();
    }

    /**
     * 通用物料搜索
     * @param platformId
     * @param pageNo
     * @param q
     * @param hasCoupon
     * @return
     * @throws ApiException
     */
    public String requestTbkDgMaterialOptional(Long platformId, Long pageNo, String q, Boolean hasCoupon, Boolean isTmall, Long startPrice, Long endPrice, String sort) throws ApiException {
        TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
        req.setPageSize(this.pageSize);
        req.setPageNo(pageNo);
        req.setPlatform(platformId);
        req.setIsTmall(isTmall);
        req.setSort(sort);
        req.setQ(q);
        if (endPrice > startPrice) {
            req.setEndPrice(endPrice);
            req.setStartPrice(startPrice);
        }
        req.setHasCoupon(hasCoupon);
        req.setAdzoneId(this.adzoneId);
        TbkDgMaterialOptionalResponse rsp = (TbkDgMaterialOptionalResponse)client.execute(req);
        itemProcService.processItemStr(rsp.getBody());
        return rsp.getBody();
    }

    /**
     * 直接获取查询商品的淘口令
     * @param q     商品查询词
     * @return
     * @throws ApiException
     */
    public JSONObject requestDgMaterialTpwd(String q) throws ApiException {
        String resStr = this.requestTbkDgMaterialOptional(1L, 1L, q, true, false, 0L, 0L, "");
        JSONObject resJsonObj = JSON.parseObject(resStr);
        JSONObject response = (JSONObject)resJsonObj.get("tbk_dg_material_optional_response");
        if (response == null) {
            return null;
        }
        JSONObject resultListObj = (JSONObject)response.get("result_list");
        if (resultListObj == null) {
            return null;
        }
        JSONArray resultArr = (JSONArray)resultListObj.get("map_data");
        if (resultArr == null) {
            return null;
        }
        JSONArray tpwdJsonArr = this.getTpwdArr(resultArr);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("tpwd_list", tpwdJsonArr);
//        System.out.println(tpwdJsonArr.size());
        return jsonObj;
//        return null;
    }

    /**
     * 获取3个淘口令的json列表
     * @param materialArr
     * @return
     * @throws ApiException
     */
    public JSONArray getTpwdArr(JSONArray materialArr) throws ApiException {
        int length = materialArr.size() >= 3 ? 3 : materialArr.size();
        JSONArray tpwdJsonArr = new JSONArray();
        for (int i = 0; i < length; i++) {
            JSONObject materialObj = materialArr.getJSONObject(i);
            String num_iid = materialObj.getString("num_iid");
            String title = materialObj.getString("title");
            String share_url = materialObj.getString("coupon_share_url") == null ? materialObj.getString("url") : materialObj.getString("coupon_share_url");
            String url = "https:" + share_url;
            String logo = materialObj.getString("pict_url");

            Float zk_final_price = materialObj.getFloat("zk_final_price");
            Float coupon_amount = materialObj.getFloat("coupon_amount");
            Float coupon_final_price = zk_final_price - coupon_amount;

            JSONObject tpwdJsonObj = this.requestTbkTpwdCreate(num_iid, title, url, logo);
            JSONObject response = tpwdJsonObj.getJSONObject("tbk_tpwd_create_response");
            if (response == null) {
                continue;
            }
            JSONObject data = response.getJSONObject("data");
            if (data == null) {
                continue;
            }
            String tpwd = data.getString("model");
            String tpwdStr = title + "\r\n"
                    + "【在售价】" + materialObj.getString("zk_final_price") + "\r\n"
                    + "【券信息】" + materialObj.getString("coupon_info") + "\r\n"
                    + "【券后价】" + Float.toString(coupon_final_price) + "\r\n"
                    + "【淘口令】" + tpwd + "\r\n"
                    + "-------------------------------\r\n"
                    + "复制这条信息，到【手机淘宝】即可查看";
            JSONObject tpwdStrJsonObj = new JSONObject();
            tpwdStrJsonObj.put("tpwd_str", tpwdStr);
            tpwdJsonArr.add(tpwdStrJsonObj);
        }
        return tpwdJsonArr;
    }

    /**
     * 从redis中获取商品详情
     * @param itemId
     * @return
     */
    public JSONObject getTbkItemInfo(String itemId) {
        String itemStr = stringRedisUtil.get(itemId);
        JSONObject itemJson = JSON.parseObject(itemStr);
        return itemJson;
    }


    /**
     * 商品详情获取
     * @param platformId
     * @param itemId
     * @return
     * @throws ApiException
     */
    public String requestTbkItemInfo(Long platformId, String itemId) throws ApiException {
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setNumIids(itemId);
        req.setPlatform(platformId);
        TbkItemInfoGetResponse rsp = (TbkItemInfoGetResponse)client.execute(req);
        return rsp.getBody();
    }


    /**
     * 获取淘口令
     * @return
     * @throws ApiException
     */
    public JSONObject requestTbkTpwdCreate(String itemId, String text, String url, String logo) throws ApiException {
        String key = "tpwd_" + itemId;
        String tpwdStr = stringRedisUtil.get(key);
        if (tpwdStr != null) {
            JSONObject tpwdJson = JSON.parseObject(tpwdStr);
            return tpwdJson;
        }

        TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
//        req.setUserId("123");
        req.setText(text);
        req.setUrl(url);
        req.setLogo(logo);
//        req.setExt("{}");
        TbkTpwdCreateResponse rsp = (TbkTpwdCreateResponse)client.execute(req);
        String tpwdBody = rsp.getBody();
        JSONObject tpwdJson = JSON.parseObject(tpwdBody);
        if (tpwdJson.getJSONObject("error_response") == null) {
            // 将淘口令缓存到redis
            this.saveTbkTpwdToRedis(itemId, tpwdBody);
        }
        return tpwdJson;
    }


    private void saveTbkTpwdToRedis(String itemId, String tpwd) {
        String key = "tpwd_" + itemId;
        if (!stringRedisUtil.exists(key)) {
            stringRedisUtil.set(key, tpwd);
        }
    }

    /**
     * 分页获取精品列表
     * @param pageNo
     * @return
     */
    public List<JPItemDo> getJPItems(Integer pageNo) {
        Integer offset = (pageNo - 1) * this.pageSize.intValue();
        List<JPItemDo> jpItemDoList = this.jpItemDoMapper.selectByLimit(offset, this.pageSize.intValue());
        return jpItemDoList;
    }


    /**
     * 根据产品id获取产品
     * @param itemId
     * @return
     */
    public JPItemDo getJPItem(String itemId) {
        JPItemDo jpItemDo = this.jpItemDoMapper.selectByItemId(itemId);
        return jpItemDo;
    }


    /**
     * 获取聚划算商品列表
     * @param pageNo    页码
     * @return
     */
    public List<JHSItemDo> getJHSItems(Integer pageNo) {
        Integer offset = (pageNo - 1) * this.pageSize.intValue();
        List<JHSItemDo> jhsItemDoList = this.jhsItemDoMapper.selectByLimit(offset, this.pageSize.intValue());
        return jhsItemDoList;
    }

    /**
     * 根据商品id获取聚划算商品
     * @param itemId
     * @return
     */
    public JHSItemDo getJHSItem(String itemId) {
        JHSItemDo jhsItemDo = this.jhsItemDoMapper.selectByItemId(itemId);
        return jhsItemDo;
    }



}
